import axios from 'axios'
import store from '@/store'
import {VueAxios} from './axios'
import qs from 'qs'
import notification from 'ant-design-vue/es/notification'

// 创建 axios 实例
const service = axios.create({
    baseURL: '/', // api base_url
    timeout: 6000 // 请求超时时间
});

const err = (error) => {
    if (error.response) {
        const data = error.response.data
        if (error.response.status === 403) {
            notification.error({message: '403 访问被禁止', description: data.message})
        }
        if (error.response.status === 401) {
            notification.error({message: '登录信息已过期', description: '请重新登录'})
            store.dispatch('Logout').then(() => {
                setTimeout(() => {
                    window.location.reload()
                }, 1500)
            })
        }
    }
    return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
    // 让每个请求携带自定义 NutzFwFront 告之后端是NutzFwFront前台
    config.headers['NutzFwFront'] = true
    return config
}, err)

// response interceptor
service.interceptors.response.use((response) => response.data, err)


const installer = {
    vm: {},
    install(Vue, router = {}) {
        Vue.use(VueAxios, router, service)
    }
}

function post(url, parameter) {
    return service({
        url: url,
        method: 'post',
        data: qs.stringify(transformParameter(parameter))
    })
}

function postJson(url, parameter) {
    return service({
        url: url,
        method: 'post',
        data: transformParameter(parameter)
    })
}

function get(url, parameter) {
    return service({
        url: url,
        method: 'get',
        data: qs.stringify(transformParameter(parameter))
    })
}

function transformParameter(parameter) {
    if (parameter == undefined || parameter == null) {
        parameter = {}
    }
    return parameter;
}

export {
    installer as VueAxios,
    service as axios,
    post as post,
    postJson as postJson,
    get as get,
}
